package com.im.services.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Base64Utils {

    public static void main(String[] args) throws Exception {

        // 编码
        String s = encodeImage("C:\\Users\\dashixin\\Pictures\\云圈\\Q6Xh-hkrzyam6844174.jpg");

        // 解码
        byte[] bytes = decodeByte(s);

        new FileOutputStream("./a.jpg").write(bytes, 0, bytes.length);
    }

    static BASE64Encoder encoder = new BASE64Encoder();
    static BASE64Decoder decoder = new BASE64Decoder();

    public static String encodeImage(String url) {
        File file = new File(url);
        ByteArrayOutputStream baos = null;
        try {
            BufferedImage bi = ImageIO.read(file);
            baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static byte[] decodeByte(String data) {
        try {
            return decoder.decodeBuffer(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}